const three = this.pageObj.getApiWidgetByAliasName('三维组件');
const prefix = this.pageObj.getVariables().find(v => v.name === 'environmentType')?.value || '';
console.log('-------------- org init -----------------')

function resetMember (member, index) {
    return {
        ...member,
        type: '1',
        title: `${member.personName || member.communicationName || `匿名${index}`}(${member.account})`,
        username: `${member.personName || member.communicationName || `匿名${index}`}`,
        userId: member.account,
        treeId: member.id || member.personId,
    }
}

const random = (num = 10) => parseInt(Math.random() * Math.pow(10, num))

function breakDataSource(item) {
    const dispatchLength = item.dispatchList?.length
    item.title = `${item.orgName}[${item.count}]`;
    item.id = item.orgId;
    item.treeId = item.orgId;
    if (item.children) {
        item.children = item.children.map(breakDataSource);
        item.type = '0'
    }

    if (dispatchLength) {
        const id = `${random(10)}-${random(10)}`;
        item.children.unshift({
            id,
            treeId: id,
            title: `调度台[${dispatchLength}]`,
            children: item.dispatchList.map(resetMember),
        })
    }

    if (item.personList) {
        item.personList.map((member, index) => {
            item.children.push(resetMember(member, index))
        });
    }

    return item
}

fetch(`/${prefix}Communication/pubCommunicationAccount/getOrgListByName`)
    .then(res => res.json())
    .then(res => {
        const { result, resultCode } = res;
        if (resultCode === '000000') {
            let dataSource = result.map(breakDataSource);
            const artemis = three?.widgetObj.artemis;

            console.log('artemis: => ', artemis)
            if (artemis) {
                dataSource = artemis.resetUsersStatus(dataSource);
            }

            this.widgetObj._option.dataSource = dataSource;
            this.widgetObj.render();
            console.log(res, dataSource)
        }
    }).catch(error => console.error(error));
